package com.ushine.web.template.mybatis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ushine.web.template.mybatis.mapper.DemoMapper;
import com.ushine.web.template.mybatis.model.DemoDO;
import com.ushine.web.template.mybatis.service.IDemoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @Author: yls
 * @Date 2022/2/7 16:13
 * @Description: mybatis的测试service
 * @Version 1.0
 **/
@Service
public class DemoServiceImpl extends ServiceImpl<DemoMapper, DemoDO> implements IDemoService {

    @Override
    @Transactional(readOnly = true)
    public DemoDO getDemoById(Long id) {
        return Optional.ofNullable(getById(id)).orElse(new DemoDO());
    }

    /**
     * 查询指定必须用 LambdaQueryWrapper
     * 具体文档：
     *  mybatis的具体文档：https://baomidou.com/pages/24112f/
     *  条件构造器：https://baomidou.com/pages/10c804/#abstractwrapper
     *  排除字段
     *  queryWrapper.select(DemoDO.class,fieldInfo -> !fieldInfo.getColumn().equals("username"));
     */
    @Override
    @Transactional(readOnly = true)
    public List<DemoDO> listDemos(String username) {

        LambdaQueryWrapper<DemoDO> queryWrapper = new LambdaQueryWrapper<>();
        // 等于
        queryWrapper.eq(DemoDO::getUsername, username)
                // 指定字段
                .select(DemoDO::getUsername, DemoDO::getId, DemoDO::getTrueName);

        List<DemoDO> list = list(queryWrapper);
        return Optional.ofNullable(list).orElse(new ArrayList<>());
    }
}
